var Play = new Class({
	initialize: function () {
		(function () {
			if (this.loading) return;
	
			var id = parseInt(location.hash.substring(1));
			if (id && (!this.game || id != this.game.id)) {
				this.load(id);
			}
		}).periodical(500, this);
	},
	
	load: function (id) {
		if (this.loading) return;
		this.loading = true;

		var t = this,
			loading = new Element('div', { id: 'loading' }).inject(document.body),
			req = new Request.JSON({url: 'server.php',
				onComplete: function (response) {
					loading.destroy();

					switch (response.result) {
						case 'error':
							location.hash = '#';
							alert(response.error);
							break;
						case 'success':
							t.setGame(Tack.Game.decompile(response.game));
							t.game.id = response.gameId;
							location.hash = '#' + t.game.id;
							break;
					}
	
					t.loading = false;
				}}).post({ action: 'get', gameId: id });
	},
	
	setGame: function (game) {
		this.game = game;
		this.player = new Tack.Player(game);
		this.console = new Tack.Console($('body').empty(), this.player, false);
		this.console.html.input.focus();
		
		this.player.play();
	}
});

window.addEvent('domready', function () {
	new Play();
});
